<template>
  <div class="send-panel">
    <div class="toolbar">
      <el-popover
        :visible="showEmojiPopover"
        trigger="click"
        placement="top"
        :teleported="false"
        @show="openPopover"
        @hide="closePopover"
        :popper-style="{
          padding: '0px 10px 10px 10px',
          width: '490px',
        }"
      >
        <template #default>
          <el-tabs v-model="activeEmoji" @click.stop>
            <el-tab-pane
              :label="emoji.name"
              :name="emoji.name"
              v-for="emoji in emojiList"
            >
              <div class="emoji-list">
                <div
                  class="emoji-item"
                  v-for="item in emoji.emojiList"
                  @click="sendEmoji(item)"
                >
                  {{ item }}
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </template>
        <template #reference>
          <i
            title="表情"
            class="iconfont icon-biaoqing"
            @click="showEmojiPopoverHandler"
          ></i>
        </template>
      </el-popover>
      <ImageChat :contactId="currentChatUser.contactId" />
      <VideoChat :contactId="currentChatUser.contactId" />
      <FileChat :contactId="currentChatUser.contactId" />
      <VoiceChat :contactId="currentChatUser.contactId" />
    </div>
    <div class="input-area" @drop="dropHandler" @dragover="dragOverHandler">
      <div class="reply-msg" v-if="replyMsgVisible">
        <div class="reply-msg-inner">
          <div class="head">
            <div v-if="replyMsgStore.getReplyMsg().messageType === 'text'">
              {{ replyMsgStore.getReplyMsg().sendUsername }}:
              {{ replyMsgStore.getReplyMsg().messageContent }}
            </div>
            <div v-if="replyMsgStore.getReplyMsg().messageType === 'image'">
              {{ replyMsgStore.getReplyMsg().sendUsername }}: [图片]
            </div>
            <div v-if="replyMsgStore.getReplyMsg().messageType === 'video'">
              {{ replyMsgStore.getReplyMsg().sendUsername }}: [视频]
            </div>
            <div v-if="replyMsgStore.getReplyMsg().messageType === 'file'">
              {{ replyMsgStore.getReplyMsg().sendUsername }}: [文件]
            </div>
            <div v-if="replyMsgStore.getReplyMsg().messageType === 'voice'">
              {{ replyMsgStore.getReplyMsg().sendUsername }}: [语音]
            </div>
          </div>
          <div class="close" @click="replyRemove">
            <i class="iconfont icon-guanbi" />
          </div>
        </div>
      </div>
      <el-input
        :rows="7"
        v-model="msgContent"
        type="textarea"
        resize="none"
        maxlength="1500"
        show-word-limit
        spellcheck="false"
        input-style="background:#f5f5f5;border:none;"
        @keydown.enter.exact.prevent="sendMessage"
        placeholder="输入信息 按enter键发送"
        @paste="pasteFile"
      />
    </div>
    <SearchAdd ref="searchAddRef"></SearchAdd>
  </div>
</template>

<script setup>
import emojiList from "@/utils/Emoji.js";
import ImageChat from "./ImageChat.vue";
import VideoChat from "./VideoChat.vue";
import FileChat from "./FileChat.vue";
import VoiceChat from "./VoiceChat.vue";
import SearchAdd from "@/views/contact/SearchAdd.vue";
import { ref, getCurrentInstance, watch } from "vue";
import { useUserInfoStore } from "@/stores/UserInfoStore";
import { useReplyMsgVisibleStore } from "@/stores/ReplyMsgVisibleStore";

const userInfoStore = useUserInfoStore();
const { proxy } = getCurrentInstance();
const replyMsgStore = useReplyMsgVisibleStore();

const props = defineProps({
  currentChatUser: {
    type: Object,
    default: {},
  },
});

const showEmojiPopover = ref(false);
const hidePopover = () => {
  showEmojiPopover.value = false;
};

const openPopover = () => {
  document.addEventListener("click", hidePopover, false);
};
const closePopover = () => {
  document.removeEventListener("click", hidePopover, false);
};

const activeEmoji = ref("笑脸");
const showEmojiPopoverHandler = () => {
  showEmojiPopover.value = true;
};
const sendEmoji = (emoji) => {
  msgContent.value = msgContent.value + emoji;
  showEmojiPopover.value = false;
};

const replyMsgVisible = ref(false);
watch(
  () => replyMsgStore.getReplyMsg(),
  () => {
    if (replyMsgStore.getReplyMsg().messageId) {
      replyMsgVisible.value = true;
    } else {
      replyMsgVisible.value = false;
    }
  },
  { deep: true }
);

const replyRemove = () => {
  replyMsgStore.setReplyMsg({}) || undefined;
};

const cleanMessage = () => {
  msgContent.value = "";
};
defineExpose({
  cleanMessage,
});
const msgContent = ref("");
let timer = null;
const sendMessage = async (e) => {
  if (e.shiftKey && e.keyCode === 13) {
    return;
  }
  e.preventDefault();
  const messageContent = msgContent.value ? msgContent.value.replace(/\s*$/g, "") : "";
  if (messageContent.trim().length === 0) {
    proxy.$message.error("请输入信息");
    return;
  }
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(async () => {
    const prefix = props.currentChatUser.contactId.substring(0, 1);
    if (prefix === "U") {
      if (replyMsgVisible.value) {
        const res = await proxy.Api.sendPrivateMessage({
          deduplicationId: proxy.UniqueId.generateUniqueUserId(),
          sendUserId: userInfoStore.getInfo().userId,
          contactId: props.currentChatUser.contactId,
          messageType: "reply",
          messageContent: messageContent,
          replyId: replyMsgStore.getReplyMsg().messageId,
        });
        if (res.code == 114) {
          proxy.Confirm({
            message: res.message,
            okfun: () => {
              addContact(props.currentChatUser.contactId, res.code);
            },
            okText: "重新申请",
          });
          return;
        } else if (res.code === 200) {
          replyMsgStore.setReplyMsg({});
          proxy.Api.updateReadMsgState(props.currentChatUser.contactId);
          proxy.$message.success("消息已发送");
        }
      } else {
        const res = await proxy.Api.sendPrivateMessage({
          deduplicationId: proxy.UniqueId.generateUniqueUserId(),
          sendUserId: userInfoStore.getInfo().userId,
          contactId: props.currentChatUser.contactId,
          messageType: "text",
          messageContent: messageContent,
        });
        if (res.code == 114) {
          proxy.Confirm({
            message: res.message,
            okfun: () => {
              addContact(props.currentChatUser.contactId, res.code);
            },
            okText: "重新申请",
          });
          return;
        } else if (res.code === 200) {
          proxy.$message.success("消息已发送");
        }
      }
      showEmojiPopover.value = false;
      cleanMessage();
    } else if (prefix === "G") {
      if (replyMsgVisible.value) {
        const res = await proxy.Api.sendClusterMessage({
          deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
          sendUserId: userInfoStore.getInfo().userId,
          contactId: props.currentChatUser.contactId,
          messageType: "reply",
          messageContent: messageContent,
          replyId: replyMsgStore.getReplyMsg().messageId,
        });
        if (res.code === 120) {
          proxy.Confirm({
            message: res.message,
            okfun: () => {
              addContact(props.currentChatUser.contactId, res.code);
            },
            okText: "重新申请",
          });
          return;
        } else if (res.code === 200) {
          replyMsgStore.setReplyMsg({});
          proxy.$message.success("消息已发送");
        }
        showEmojiPopover.value = false;
        cleanMessage();
      } else {
        const res = await proxy.Api.sendClusterMessage({
          deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
          sendUserId: userInfoStore.getInfo().userId,
          contactId: props.currentChatUser.contactId,
          messageType: "text",
          messageContent: messageContent,
        });
        if (res.code === 119) {
          proxy.Confirm({
            message: res.message,
            okfun: () => {
              addContact(props.currentChatUser.contactId, res.code);
            },
            okText: "重新申请",
          });
          return;
        } else if (res.code === 200) {
          proxy.$message.success("消息已发送");
        }
      }
      showEmojiPopover.value = false;
      cleanMessage();
    }
    timer = null;
  }, 200);
};

const searchAddRef = ref();
const addContact = (contactId, code) => {
  searchAddRef.value.show({
    contactId,
    contactType: code == 114 ? 0 : 1,
  });
};

const dragOverHandler = (e) => {
  e.preventDefault();
};

const dropHandler = async (event) => {
  event.preventDefault();
  const files = event.dataTransfer.files;
  if (files[0].size > 150 * 1024 * 1024) {
    proxy.$message.error("文件大于150M");
    return;
  }
  const prefix = props.currentChatUser.contactId.substring(0, 1);
  const formData = new FormData();
  formData.append("file", files[0]);
  const resUpload = await proxy.Api.minioUpload(formData);
  if (files[0].type.startsWith("image/")) {
    if (prefix === "U") {
      const res = await proxy.Api.sendPrivateMessage({
        deduplicationId: proxy.UniqueId.generateUniqueUserId(),
        sendUserId: userInfoStore.getInfo().userId,
        contactId: props.currentChatUser.contactId,
        messageType: "image",
        messageContent: resUpload.data,
      });
      if (res.code == 114) {
        proxy.Confirm({
          message: res.message,
          okfun: () => {
            addContact(props.currentChatUser.contactId, res.code);
          },
          okText: "重新申请",
        });
        return;
      } else if (res.code === 200) {
        proxy.Api.updateReadMsgState(props.currentChatUser.contactId);
        proxy.$message.success("图片已发送");
      }
    } else if (prefix === "G") {
      const res = await proxy.Api.sendClusterMessage({
        deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
        sendUserId: userInfoStore.getInfo().userId,
        contactId: props.currentChatUser.contactId,
        messageType: "image",
        messageContent: resUpload.data,
      });
      if (res.code === 119) {
        proxy.Confirm({
          message: res.message,
          okfun: () => {
            addContact(props.currentChatUser.contactId, res.code);
          },
          okText: "重新申请",
        });
        return;
      } else if (res.code === 200) {
        proxy.$message.success("图片已发送");
      }
    }
  } else if (files[0].type.startsWith("video/")) {
    if (prefix === "U") {
      const res = await proxy.Api.sendPrivateMessage({
        deduplicationId: proxy.UniqueId.generateUniqueUserId(),
        sendUserId: userInfoStore.getInfo().userId,
        contactId: props.currentChatUser.contactId,
        messageType: "video",
        messageContent: resUpload.data,
        fileSize: files[0].size,
        fileName: files[0].name,
      });
      if (res.code == 114) {
        proxy.Confirm({
          message: res.message,
          okfun: () => {
            addContact(props.currentChatUser.contactId, res.code);
          },
          okText: "重新申请",
        });
        return;
      } else if (res.code === 200) {
        proxy.Api.updateReadMsgState(props.currentChatUser.contactId);
        proxy.$message.success("视频已发送");
      }
    } else if (prefix === "G") {
      const res = await proxy.Api.sendClusterMessage({
        deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
        sendUserId: userInfoStore.getInfo().userId,
        contactId: props.currentChatUser.contactId,
        messageType: "video",
        messageContent: resUpload.data,
        fileSize: files[0].size,
        fileName: files[0].name,
      });
      if (res.code === 119) {
        proxy.Confirm({
          message: res.message,
          okfun: () => {
            addContact(props.currentChatUser.contactId, res.code);
          },
          okText: "重新申请",
        });
        return;
      } else if (res.code === 200) {
        proxy.$message.success("视频已发送");
      }
    }
  } else {
    if (prefix === "U") {
      const res = await proxy.Api.sendPrivateMessage({
        deduplicationId: proxy.UniqueId.generateUniqueUserId(),
        sendUserId: userInfoStore.getInfo().userId,
        contactId: props.currentChatUser.contactId,
        messageType: "file",
        messageContent: resUpload.data,
        fileSize: files[0].size,
        fileName: files[0].name,
      });
      if (res.code == 114) {
        proxy.Confirm({
          message: res.message,
          okfun: () => {
            addContact(props.currentChatUser.contactId, res.code);
          },
          okText: "重新申请",
        });
        return;
      } else if (res.code === 200) {
        proxy.Api.updateReadMsgState(props.currentChatUser.contactId);
        proxy.$message.success("文件已发送");
      }
    } else if (prefix === "G") {
      const res = await proxy.Api.sendClusterMessage({
        deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
        sendUserId: userInfoStore.getInfo().userId,
        contactId: props.currentChatUser.contactId,
        messageType: "file",
        messageContent: resUpload.data,
        fileSize: files[0].size,
        fileName: files[0].name,
      });
      if (res.code === 119) {
        proxy.Confirm({
          message: res.message,
          okfun: () => {
            addContact(props.currentChatUser.contactId, res.code);
          },
          okText: "重新申请",
        });
        return;
      } else if (res.code === 200) {
        proxy.$message.success("文件已发送");
      }
    }
  }
};

const pasteFile = async (event) => {
  const items = event.clipboardData && event.clipboardData.items;
  const file = getImageFileFromClipboard(items);
  if (proxy.Utils.isEmpty(file)) {
    return;
  }
  const formData = new FormData();
  formData.append("file", file);
  const resUpload = await proxy.Api.minioUpload(formData);
  const prefix = props.currentChatUser.contactId.substring(0, 1);
  if (prefix === "U") {
    const res = await proxy.Api.sendPrivateMessage({
      deduplicationId: proxy.UniqueId.generateUniqueUserId(),
      sendUserId: userInfoStore.getInfo().userId,
      contactId: props.currentChatUser.contactId,
      messageType: "image",
      messageContent: resUpload.data,
    });
    if (res.code == 114) {
      proxy.Confirm({
        message: res.message,
        okfun: () => {
          addContact(props.currentChatUser.contactId, res.code);
        },
        okText: "重新申请",
      });
      return;
    } else if (res.code === 200) {
      proxy.Api.updateReadMsgState(props.currentChatUser.contactId);
      proxy.$message.success("图片已发送");
    }
  } else if (prefix === "G") {
    const res = await proxy.Api.sendClusterMessage({
      deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
      sendUserId: userInfoStore.getInfo().userId,
      contactId: props.currentChatUser.contactId,
      messageType: "image",
      messageContent: resUpload.data,
    });
    if (res.code === 119) {
      proxy.Confirm({
        message: res.message,
        okfun: () => {
          addContact(props.currentChatUser.contactId, res.code);
        },
        okText: "重新申请",
      });
      return;
    } else if (res.code === 200) {
      proxy.$message.success("图片已发送");
    }
  }
};

const getImageFileFromClipboard = (items) => {
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf("image") !== -1) {
      const blob = items[i].getAsFile();
      const file = new File([blob], new Date().getTime() + ".image");
      return file;
    }
  }
  return null;
};
</script>

<style lang="scss" scoped>
.emoji-list {
  .emoji-item {
    float: left;
    font-size: 23px;
    padding: 2px;
    text-align: center;
    border-radius: 3px;
    margin-left: 10px;
    margin-top: 5px;
    cursor: pointer;

    &:hover {
      background: #ddd;
    }
  }
}

.send-panel {
  height: 200px;

  .toolbar {
    height: 40px;
    display: flex;
    align-items: center;
    padding-left: 10px;
    border-top: 1px solid #ddd;
    border-bottom: 1px solid #ddd;
    background-color: #eaeaea;

    .iconfont {
      cursor: pointer;
    }

    :deep(.el-tabs__header) {
      margin-bottom: 0px;
    }
  }

  .input-area {
    padding: 0px;
    outline: none;
    height: 160px;
    overflow: auto;
    word-wrap: break-word;
    word-break: break-all;

    :deep(.el-textarea__inner) {
      box-shadow: none;
    }

    :deep(.el-input__count) {
      background: none;
      right: 12px;
    }

    .reply-msg {
      height: 30px;
      padding: 1px 10px;
      width: 40%;
      .reply-msg-inner {
        background-color: #ddd;
        padding: 5px 20px 5px 5px;
        border-radius: 10px;
        font-size: 12px;
        position: relative;

        .head {
          margin-bottom: 5px;
          display: flex;
          .name {
            margin-right: 5px;
          }
        }

        .close {
          position: absolute;
          right: 5px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
          i {
            font-size: 10px;
          }
        }
      }
    }
  }

  ::-webkit-scrollbar {
    display: none;
  }
}
</style>
